﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using ChiDao.Business.Service.Impl;
using ChiDao.Site.Models;
using Ext.Net.MVC;
using Ext.Net;
using ChiDao.Business.Models.FlowProcess;
using System.Xml;
using System.Web.Script.Serialization;
using ChiDao.Business.Service;
using ChiDao.Component.Utils;
using ChiDao.Business.Service.AttachAttribute;

namespace ChiDao.Site.Web.Controllers
{
    [Export]
    public class HolidayDocumentController : BaseController
    {
        [Import]
        public IHolidayDocumentService HolidayDocumentService { get; set; }
        [Import]
        public IBaklogTaskService BaklogTaskService { get; set; }
        [Import]
        public IProcessNodeService ProcessNodeService { get; set; }

        public ActionResult QueryHolidayDocument(string selectHolidayDocument, string processState)
        {
            this.GetCmp<TextField>("txtRequestPerson").Disable();
            if (string.IsNullOrEmpty(processState) || processState == "0")
            {
                this.GetCmp<Button>("btnBack").Disable();
                this.GetCmp<Button>("btnNext").Disable();
            }
            else if (processState == "1")
            {
                this.GetCmp<Button>("btnBack").Disable();
                if (HolidayDocumentService.OnlyPreviewHolidayDocument(selectHolidayDocument))
                {
                    this.GetCmp<Button>("btnSave").Disable();
                    this.GetCmp<Button>("btnNext").Disable();
                }
            }
            else
            {
                this.GetCmp<Button>("btnSave").Disable();
            }
            return View(HolidayDocumentService.QueryHolidayDocument(selectHolidayDocument, User.Identity.Name));
        }

        [DirectMethod]
        public ActionResult SaveData(string id, DateTime? requestDate, string description)
        {
            if (requestDate != null)
            {
                HolidayDocumentService.SaveHolidayDocument(Guid.Parse(id), User.Identity.Name, Convert.ToDateTime(requestDate), description);
                X.Msg.Confirm("Confirm", "Save successful!", new MessageBoxButtonsConfig
                {
                    Ok = new MessageBoxButtonConfig { Handler = "saveSuccess()", Text = "Ok" }
                }).Show();
            }
            else
            {
                X.Msg.Confirm("Confirm", "申请日期不能为空！", new MessageBoxButtonsConfig
                {
                    Ok = new MessageBoxButtonConfig { Text = "Ok" }
                }).Show();
            }
            return this.Direct();
        }

        [DirectMethod]
        public ActionResult BackData(string id)
        {
            string currentProcessNode = string.Empty;
            BaklogTaskService.GetNextProcessNodeCode(User.Identity.Name, id, ref currentProcessNode);
            if (!string.IsNullOrEmpty(currentProcessNode))
            {
                List<ProcessNodeView> currentNodeList = ProcessNodeService.QuerySpecProcessNode("HolidayDocument", false, currentProcessNode);
                if (currentNodeList != null && currentNodeList.Count == 1)
                {
                    List<ProcessNodeView> preNodeList = ProcessNodeService.QuerySpecProcessNode("HolidayDocument", false, currentNodeList[0].PreviousNodeCode);
                    if (preNodeList != null && preNodeList.Count == 1)
                    {
                        //更新待办
                        List<BaklogTaskView> originalList = BaklogTaskService.QueryBaklogTask(User.Identity.Name, id);

                        foreach (BaklogTaskView update in originalList)
                        {
                            update.ApprovalOpinion = "回退";
                            update.HandleState = "1";
                            update.ProcessTime = DateTime.Now;
                        }
                        BaklogTaskService.UpdateBaklogTask(originalList);

                        if (preNodeList[0].NodeType == "0")
                        {
                            HolidayDocumentService.UpdateHolidayDocument(Guid.Parse(id), DateTime.Now, null, "0");
                        }
                        else
                        {
                            //添加待办
                            originalList = BaklogTaskService.QueryBaklogTask(User.Identity.Name, id);
                            if (originalList.Count == 0)
                            {
                                HolidayDocumentView holidayDocumentView = HolidayDocumentService.GetHolidayDocumentByID(id);
                                List<BaklogTaskView> addList = new List<BaklogTaskView>();
                                string[] processPersonArr = preNodeList[0].DefaultProcessPerson.Split(',');
                                foreach (string processPerson in processPersonArr)
                                {
                                    BaklogTaskView add = new BaklogTaskView();
                                    add.ID = GuidHelper.NewGuid();
                                    add.ProcessID = id;
                                    add.TaskName = "请假单";
                                    add.RequestPerson = holidayDocumentView.RequestPerson;
                                    add.CurrentProcessNodeCode = preNodeList[0].NodeCode;
                                    add.CurrentProcessNodeName = preNodeList[0].NodeName;
                                    add.NextProcessNodeCode = preNodeList[0].NextNodeCode;
                                    add.HandleState = "0";
                                    add.CurrentProcessPerson = processPerson;
                                    add.ProcessTime = DateTime.Now;
                                    addList.Add(add);
                                }
                                BaklogTaskService.AddBaklogTask(addList);
                            }
                        }

                        X.Msg.Confirm("Confirm", "回退成功!", new MessageBoxButtonsConfig
                        {
                            Ok = new MessageBoxButtonConfig { Text = "Ok" }
                        }).Show();
                        return this.Direct();
                    }
                }
            }

            X.Msg.Confirm("Confirm", "数据不对！", new MessageBoxButtonsConfig
            {
                Ok = new MessageBoxButtonConfig { Text = "Ok" }
            }).Show();
            return this.Direct();
        }

        [DirectMethod]
        public ActionResult CirculationWindow()
        {
            return new Ext.Net.MVC.PartialViewResult { ViewName = "CirculationWindow" };
        }

        public ActionResult GenerateGraph(string processID, string processCode)
        {
            WorkFlowView workFlowView = new WorkFlowView();
            workFlowView.lstProcessNode = ProcessNodeService.QueryProcessNode(processCode);
            workFlowView.HasDocument = false;
            HolidayDocumentView holidayDocument = HolidayDocumentService.GetHolidayDocumentByID(processID);
            if (holidayDocument != null)
            {
                workFlowView.HasDocument = true;
                string handleState=workFlowView.HandleState = holidayDocument.HandleState;
                if (handleState == "1")
                {
                    handleState = "0";
                }
                if (holidayDocument.HandleState == "0")
                {
                    List<ProcessNodeView> currentProcessNode = ProcessNodeService.QuerySpecProcessNode(processCode, true, "", "0");
                    workFlowView.CurrentOrderNo = currentProcessNode[0].OrderNo;
                }
                else
                {
                    if (handleState == "0" || handleState == "3")
                    {
                        List<BaklogTaskView> lstWorkFlowBaklogTask = BaklogTaskService.QueryBaklogTask(User.Identity.Name, processID, handleState);
                        if (lstWorkFlowBaklogTask.Count > 0)
                        {
                            List<ProcessNodeView> currentProcessNode = ProcessNodeService.QuerySpecProcessNode(processCode, false, lstWorkFlowBaklogTask[0].CurrentProcessNodeCode);
                            workFlowView.CurrentOrderNo = currentProcessNode[0].OrderNo;
                        }
                    }
                }
            }
            string jsonStr = JSON.Serialize(workFlowView);
            return PartialView("PreviewGraph", jsonStr);
        }

        [WebPage]
        public ActionResult QueryRequestHolidayDocument()
        {
            return View(HolidayDocumentService.QueryRequestHolidayDocument(User.Identity.Name));
        }

        [WebPage]
        public RedirectToRouteResult QueryBaklogTask()
        {
            return this.RedirectToAction("QueryBaklogTask", "BaklogTask");
        }
    }
}